# -*- coding: utf-8 -*-

from json import dumps

from django.utils.http import urlquote

from django.utils.encoding import iri_to_uri
from django.utils.encoding import smart_unicode

from place.models import Place

from codename_bamboo.preference import ONE_LONGITUDE
from codename_bamboo.preference import DEFAULT_RADIUS
from codename_bamboo.preference import DEFAULT_QUERY_LENGTH

def _handle_place_query(request, keyword, index):
    """
    Exact matched place data from mongodb
    """
    request.encoding = 'utf-8'
    print(request.GET)
    index = int(index)
    next_query = prev_query = None
    latitude = float(request.GET['latitude'])
    longitude = float(request.GET['longitude'])

    if 'radius' in request.GET:
        radius = request.GET['radius']
    else: 
        radius = DEFAULT_RADIUS

    distance = radius / ONE_LONGITUDE

    query_set = Place.objects(location__within_distance=([latitude, longitude], distance), name__icontains=(keyword))

    print(len(query_set))
    if len(query_set) > 0:
        places = []
        print(index)
        query_start = index * DEFAULT_QUERY_LENGTH
        query_end   = query_start + DEFAULT_QUERY_LENGTH
        query = query_set[query_start:query_end]
        for q in query:
            dict = { 'uid': str(q.uid)
                    ,'name': q.name
                    ,'latitude': q.location[0]
                    ,'longitude': q.location[1]
                    ,'address': q.address
                    }
            if len(q.subjects) > 0:
                dict['image'] = str(q.subjects[0].image.grid_id)
                dict['thumb'] = str(q.subjects[0].thumb.grid_id)

            if q.description:
                dict['description'] = q.description

            places.append(dict)

        # Contruct next and previous page index
        query_length = int(len(query_set) / DEFAULT_QUERY_LENGTH)
        if query_length > index:
            next_query = '/search/place/' + iri_to_uri(keyword) + '/' + str(index + 1)
        elif index > 0:
            prev_query = '/search/place/' + iri_to_uri(keyword) + '/' + str(index - 1)

        return dumps({'ok':True
                    , 'places': places
                    , 'next': next_query
                    , 'prev':prev_query
                    })
    else:
        return dumps({'ok': False})

def _handle_search_place(request, keyword, index):
    """
    Exact matched place data from mongodb
    """
    request.encoding = 'utf-8'
    print(request.GET)
    index = int(index)
    next_query = prev_query = None
    latitude = float(request.GET['latitude'])
    longitude = float(request.GET['longitude'])

    if 'radius' in request.GET:
        radius = request.GET['radius']
    else: 
        radius = DEFAULT_RADIUS

    distance = radius / ONE_LONGITUDE

    query_set = Place.objects(location__within_distance=([latitude, longitude], distance), name__icontains=(keyword))

    print(len(query_set))
    if len(query_set) > 0:
        places = []
        print(index)
        query_start = index * DEFAULT_QUERY_LENGTH
        query_end   = query_start + DEFAULT_QUERY_LENGTH
        query = query_set[query_start:query_end]
        for q in query:
            d = { 'uid': str(q.uid)
                 ,'name': q.name
                 ,'latitude': q.location[0]
                 ,'longitude': q.location[1]
                 ,'address': q.address
                }
            if len(q.subjects) > 0:
                d['image'] = str(q.subjects[0].image.grid_id)
                d['thumb'] = str(q.subjects[0].thumb.grid_id)

            if q.description:
                d['description'] = q.description

            places.append(d)

        # Contruct next and previous page index
        query_length = int(len(query_set) / DEFAULT_QUERY_LENGTH)
        if query_length > index:
            next_query = '/search/place/' + iri_to_uri(keyword) + '/' + str(index + 1)
        elif index > 0:
            prev_query = '/search/place/' + iri_to_uri(keyword) + '/' + str(index - 1)

        return {'places': places ,'next': next_query ,'prev':prev_query}
    else:
        return False        
